<?php
App::uses('AppController', 'Controller');
/**
 * Games Controller
 *
 * @property Game $Game
 * @property PaginatorComponent $Paginator
 */
class GamesController extends AppController {

/**
 * Components
 *
 * @var array
 */
	public $components = array('Paginator');

	
/**
 * admin_index method
 *
 * @return void
 */
	public function admin_index() {
		$this->Game->recursive = 0;
		$this->set('games', $this->Paginator->paginate());
		$this->set('title_layout', 'Các game trên hệ thống');
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_view($id = null) {
		if (!$this->Game->exists($id)) {
			throw new NotFoundException(__('Invalid game'));
		}
		$options = array('conditions' => array('Game.' . $this->Game->primaryKey => $id));
		$this->set('game', $this->Game->find('first', $options));
		$this->set('title_layout', 'Xem chi tiết game');
	}

/**
 * add method
 *
 * @return void
 */
	public function admin_add() {
		$this->loadModel('GamesSystem');
		if ($this->request->is('post')) {
			$this->request->data['Game']['alias'] = $this->get_alias($this->request->data['Game']['name']);
			$save = true;
			//upload image
			$result = $this->uploadFile(APP . 'webroot/img/data/images-game/thumbnail/', 'Game', 'thumbnail');
			if($result['status'] == true) {
				$thumbnail = '/img/data/images-game/thumbnail/' . $result['filename'];
				$this->request->data['Game']['thumbnail'] = $thumbnail;
			}else {
				$this->Session->setFlash('<button class="close" data-dismiss="alert" type="button">×</button>Không upload được ảnh đại diện.', 'default', array('class' => 'alert alert-error'), 'bad');
			}
			
			//upload file android
			if($this->request->data['Game']['android']['name'] != ''){
				$android = $this->uploadFile(APP . 'webroot/files/data/download/', 'Game', 'android');
				if($android['status'] == true) {
					$android = '/files/data/download/' . $android['filename'];
					$this->request->data['GamesSystem']['download'] = $android;
				}else {
					$errors[] = 'Không upload được game cho android';
					// $save = false;
				}
			}else {
				$android = '';
				$errors[] = 'Chưa upload game cho Android';
			}
			
			
			//ios
			if($this->request->data['Game']['ios']['name'] != ''){
				$ios = $this->uploadFile(APP . 'webroot/files/data/download/', 'Game', 'ios');
				if($ios['status'] == true) {
					$ios = '/files/data/download/' . $ios['filename'];
					$this->request->data['GamesSystem']['download'] = $ios;
				}else {
					$errors[] = 'Không upload được game cho iOS';
					// $save = false;
				}
			}else {
				$ios = '';
				$errors[] = 'Chưa upload game cho iOS';
			}
			//windowsphone
			if($this->request->data['Game']['windowsphone']['name'] != ''){
				$windowsphone = $this->uploadFile(APP . 'webroot/files/data/download/', 'Game', 'windowsphone');
				if($windowsphone['status'] == true) {
					$windowsphone = '/files/data/download/' . $windowsphone['filename'];
					$this->request->data['GamesSystem']['download'] = $windowsphone;
				}else {
					$errors[] = 'Không upload được game cho Windows phone';
					// $save = false;
				}
			}else {
				$windowsphone = '';
				$errors[] = 'Chưa upload game cho Windows phone';
			}
			
			
			//pr($errors); exit;
			
			
			
			
			if($save == true){
				$this->Game->create();
				$this->check_tag($this->request->data['Tag']['Tag']);
				if ($this->Game->save($this->request->data)) {
					// truy van tu bang GamesSystem
					$this->loadModel('GamesSystem');
					$id = $this->Game->id;
					$gamesytem = $this->GamesSystem->find('all',
						array(
							'conditions' => array(
								'game_id' => $id
							),
							'recursive' => -1
						)
					);
					// pr($gamesytem);
					//luu link download vao bang gamessystem
					foreach($gamesytem as $system){
						switch($system['GamesSystem']['system_id']){
							case 1 :
								$option = array(
									'id' => $system['GamesSystem']['id'],
									'game_id' => $system['GamesSystem']['game_id'],
									'system_id' => $system['GamesSystem']['system_id'],
									'download' => $android,
								);
								$this->GamesSystem->create();
								$this->GamesSystem->save($option);
								break;
								
							case 2 :
								$option = array(
									'id' => $system['GamesSystem']['id'],
									'game_id' => $system['GamesSystem']['game_id'],
									'system_id' => $system['GamesSystem']['system_id'],
									'download' => $ios,
								);
								$this->GamesSystem->create();
								$this->GamesSystem->save($option);
								break;
								
							case 3 :
								$option = array(
									'id' => $system['GamesSystem']['id'],
									'game_id' => $system['GamesSystem']['game_id'],
									'system_id' => $system['GamesSystem']['system_id'],
									'download' => $windowsphone,
								);
								$this->GamesSystem->create();
								$this->GamesSystem->save($option);
								break;
								
							
						}
						
					}
					$this->Session->setFlash('<button class="close" data-dismiss="alert" type="button">×</button>Thêm game mới thành công.', 'default', array('class' => 'alert alert-success'), 'good');
					if(!empty($errors)){
						$this->set('errors', $errors);
					}else {
						return $this->redirect(array('action' => 'admin_index'));
					}
					
				} else {
					$this->Session->setFlash('<button class="close" data-dismiss="alert" type="button">×</button>Thêm game mới thất bại.', 'default', array('class' => 'alert alert-error'), 'bad');
				}
				
				
				
			}
			
			
		}
		$publishers = $this->Game->Publisher->find('list');
		$users = $this->Game->User->find('list');
		$categories = $this->Game->Category->find('list');
		$genres = $this->Game->Genre->find('list');
		$systems = $this->Game->System->find('list');
		$tags = $this->Game->Tag->find('list');
		$this->set(compact('publishers', 'users', 'categories', 'genres', 'systems', 'tags'));
		$this->set('title_layout', 'Thêm game mới');
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_edit($id = null) {
		if (!$this->Game->exists($id)) {
			throw new NotFoundException(__('Invalid game'));
		}
		$this->Game->validator()->remove('thumbnail');
		if ($this->request->is(array('post', 'put'))) {
			
			$this->request->data['Game']['alias'] = $this->get_alias($this->request->data['Game']['name']);
			$save = true;
			//upload image
			if($this->request->data['Game']['thumbnail']['name'] != '') {
				$result = $this->uploadFile(APP . 'webroot/img/data/images-game/thumbnail/', 'Game', 'thumbnail');
				if($result['status'] == true) {
					$thumbnail = '/img/data/images-game/thumbnail/' . $result['filename'];
					$this->request->data['Game']['thumbnail'] = $thumbnail;
				}else {
					$this->Session->setFlash('<button class="close" data-dismiss="alert" type="button">×</button>Không upload được ảnh đại diện.', 'default', array('class' => 'alert alert-error'), 'bad');
				}
			}else {
				unset($this->request->data['Game']['thumbnail']);
			}
			
			
			//upload file android
			if($this->request->data['Game']['android']['name'] != ''){
				$android = $this->uploadFile(APP . 'webroot/files/data/download/', 'Game', 'android');
				if($android['status'] == true) {
					$android = '/files/data/download/' . $android['filename'];
					$this->request->data['GamesSystem']['download'] = $android;
				}else {
					$errors[] = 'Không upload được game cho android';
					// $save = false;
				}
			}else {
				unset($this->request->data['Game']['android']);
			}
			
			
			//ios
			if($this->request->data['Game']['ios']['name'] != ''){
				$ios = $this->uploadFile(APP . 'webroot/files/data/download/', 'Game', 'ios');
				if($ios['status'] == true) {
					$ios = '/files/data/download/' . $ios['filename'];
					$this->request->data['GamesSystem']['download'] = $ios;
				}else {
					$errors[] = 'Không upload được game cho iOS';
					// $save = false;
				}
			}else {
				unset($this->request->data['Game']['ios']);
			}
			//windowsphone
			if($this->request->data['Game']['windowsphone']['name'] != ''){
				$windowsphone = $this->uploadFile(APP . 'webroot/files/data/download/', 'Game', 'windowsphone');
				if($windowsphone['status'] == true) {
					$windowsphone = '/files/data/download/' . $windowsphone['filename'];
					$this->request->data['GamesSystem']['download'] = $windowsphone;
				}else {
					$errors[] = 'Không upload được game cho Windows phone';
					// $save = false;
				}
			}else {
				unset($this->request->data['Game']['windowsphone']);
			}
			
			
			//pr($errors); exit;
			
			
			
			
			if($save == true){
				$this->check_tag($this->request->data['Tag']['Tag']);
				if ($this->Game->save($this->request->data)) {
					// truy van tu bang GamesSystem
					$this->loadModel('GamesSystem');
					$id = $this->Game->id;
					$gamesytem = $this->GamesSystem->find('all',
						array(
							'conditions' => array(
								'game_id' => $id
							),
							'recursive' => -1
						)
					);
					// pr($gamesytem);
					//luu link download vao bang gamessystem
					foreach($gamesytem as $system){
						switch($system['GamesSystem']['system_id']){
							case 1 :
								if(isset($this->request->data['Game']['android'])){
									$option = array(
										'id' => $system['GamesSystem']['id'],
										'game_id' => $system['GamesSystem']['game_id'],
										'system_id' => $system['GamesSystem']['system_id'],
										'download' => $android,
									);
									$this->GamesSystem->create();
									$this->GamesSystem->save($option);
								}
								break;
								
							case 2 :
								if(isset($this->request->data['Game']['ios'])){
									$option = array(
										'id' => $system['GamesSystem']['id'],
										'game_id' => $system['GamesSystem']['game_id'],
										'system_id' => $system['GamesSystem']['system_id'],
										'download' => $ios,
									);
									$this->GamesSystem->create();
									$this->GamesSystem->save($option);
								}
								break;
								
							case 3 :
								if(isset($this->request->data['Game']['windowsphone'])) {
									$option = array(
										'id' => $system['GamesSystem']['id'],
										'game_id' => $system['GamesSystem']['game_id'],
										'system_id' => $system['GamesSystem']['system_id'],
										'download' => $windowsphone,
									);
									$this->GamesSystem->create();
									$this->GamesSystem->save($option);
								}
								break;
								
							
						}
						
					}
					$this->Session->setFlash('<button class="close" data-dismiss="alert" type="button">×</button>Thêm game mới thành công.', 'default', array('class' => 'alert alert-success'), 'good');
					
					return $this->redirect(array('action' => 'admin_index'));
				
					
				} else {
					$this->Session->setFlash('<button class="close" data-dismiss="alert" type="button">×</button>Thêm game mới thất bại.', 'default', array('class' => 'alert alert-error'), 'bad');
				}
				
				
				
			}	
			
		} else {
			$options = array('conditions' => array('Game.' . $this->Game->primaryKey => $id));
			$this->request->data = $this->Game->find('first', $options);
			if(!empty($this->request->data['Tag'])) {
				foreach($this->request->data['Tag'] as $tag) {
					$tag_list[] = $tag['name'];
				}
				$tags = implode(', ', $tag_list);
			}else {
				$tags = null;
			}
		}
		$publishers = $this->Game->Publisher->find('list');
		$users = $this->Game->User->find('list');
		$categories = $this->Game->Category->find('list');
		$genres = $this->Game->Genre->find('list');
		$systems = $this->Game->System->find('list');
		//$tags = $this->Game->Tag->find('list');
		$this->set('title_layout', 'Sửa thông tin game');
		$this->set(compact('publishers', 'users', 'categories', 'genres', 'systems', 'tags'));
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_delete($id = null) {
		$this->Game->id = $id;
		if (!$this->Game->exists()) {
			throw new NotFoundException(__('Invalid game'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->Game->delete()) {
			$this->Session->setFlash(__('The game has been deleted.'));
		} else {
			$this->Session->setFlash(__('The game could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'admin_index'));
	}
	
	/* frontend */
	public function index() {
		//phan detect mobile
		$os = $this->getDevice();
		
		$this->Session->write('os', $os);
		$os = $this->Session->read('os');
		if ($os === ""){
			$os = $this->getDevice();
		}
		
		if ($os != ""){
				$gamehot = $this->Game->find('all',
					array(
						'limit' => 6,
						'conditions' => array('Game.view >=' => 1000),
						'contain' => array('Genre', 'System'),
						'joins' =>array(
							array(
								'table' => 'games_systems',
								'alias' => 'GameSystem',
								'conditions' => 'GameSystem.game_id = Game.id'
							),
							array(
								'table' => 'systems',
								'alias' => 'System',
								'conditions' => 'GameSystem.system_id = System.id'
							)
						),
						'conditions' => array('system_id' => $os),
					)
				);
				
				$gamenew = $this->Game->find('all',
					array(
						'limit' => 6,
						'order' => array('Game.created' => 'DESC'),
						'contain' => array('Genre', 'System'),
						'joins' =>array(
							array(
								'table' => 'games_systems',
								'alias' => 'GameSystem',
								'conditions' => 'GameSystem.game_id = Game.id'
							),
							array(
								'table' => 'systems',
								'alias' => 'System',
								'conditions' => 'GameSystem.system_id = System.id'
							)
						),
						'conditions' => array('system_id' => $os),
					)
				);		
		}else{
				$gamehot = $this->Game->find('all',
					array(
						'limit' => 6,
						'conditions' => array('Game.view >=' => 1000),
						'contain' => array('Genre', 'System')
					)
				);
				
				$gamenew = $this->Game->find('all',
					array(
						'limit' => 6,
						'order' => array('Game.created' => 'DESC'),
						'contain' => array('Genre', 'System')
					)
				);
		}
		$this->set(compact('gamehot', 'gamenew'));
		$this->set('os', $os);
	}
	
	//menu category
	public function menu_category() {
		$this->loadModel('Category');
		$categories = $this->Category->find('all',
			array(
				'recursive' => -1
			)
		);
		$this->set('categories', $categories);
		return $categories;
	}
	
	
	//menu genre
	public function menu_genre() {
		$this->loadModel('Genre');
		$genres = $this->Genre->find('all',
			array(
				'recursive' => -1
			)
		);
		$this->set('genres', $genres);
		return $genres;
	}
	
	//get game by category
	public function get_game_by_category($id, $alias) {
		if(!$id) {
			$this->Session->setFlash('Không có ứng dụng này');
		} 
		$os = $this->getDevice();
		
		$this->Session->write('os', $os);
		$os = $this->Session->read('os');
		if ($os === ""){
			$os = $this->getDevice();
		}
		
		if($os != ''){
			$this->paginate = array(
				'contain' => array(
					'Genre', 
					'System', 
					'Category'
				),
				'joins' =>array(
					array(
						'table' => 'games_categories',
						'alias' => 'GameCategory',
						'conditions' => 'GameCategory.game_id = Game.id'
					),
					array(
						'table' => 'categories',
						'alias' => 'Category',
						'conditions' => 'GameCategory.category_id = Category.id'
					),
					array(
						'table' => 'games_systems',
						'alias' => 'GameSystem',
						'conditions' => 'GameSystem.game_id = Game.id'
					),
					array(
						'table' => 'systems',
						'alias' => 'System',
						'conditions' => 'GameSystem.system_id = System.id'
					)
				),
				
				
				'conditions' => array('category_id' => $id, 'system_id' => $os),
				'limit' => 6
			);
		}else{
			$this->paginate = array(
				'contain' => array(
					'Genre', 
					'System', 
					'Category'
				),
				'joins' =>array(
						array(
							'table' => 'games_categories',
							'alias' => 'GameCategory',
							'conditions' => 'GameCategory.game_id = Game.id'
						),
						array(
							'table' => 'categories',
							'alias' => 'Category',
							'conditions' => 'GameCategory.category_id = Category.id'
						)
					),
					'conditions' => array('category_id' => $id),
					'limit' => 6
			);
		}
		
		//pr( $this->paginate()); exit;
		$this->set('os', $os);
		$this->set('games', $this->paginate());
	}
	
	
	//get game by category
	public function get_game_by_genre($id, $alias) {
		if(!$id) {
			$this->Session->setFlash('Không có thể loại game này');
		} 
		$os = $this->getDevice();
		
		$this->Session->write('os', $os);
		$os = $this->Session->read('os');
		if ($os === ""){
			$os = $this->getDevice();
		}
		
		if($os != '') {
		
			$this->paginate = array(
				'contain' => array(
					'Genre', 
					'System', 
					'Category'
				),
				'joins' =>array(
						array(
							'table' => 'games_genres',
							'alias' => 'GameGenre',
							'conditions' => 'GameGenre.game_id = Game.id'
						),
						array(
							'table' => 'genres',
							'alias' => 'Genre',
							'conditions' => 'GameGenre.genre_id = Genre.id'
						),
						array(
							'table' => 'games_systems',
							'alias' => 'GameSystem',
							'conditions' => 'GameSystem.game_id = Game.id'
						),
						array(
							'table' => 'systems',
							'alias' => 'System',
							'conditions' => 'GameSystem.system_id = System.id'
						)
					),
					'conditions' => array('genre_id' => $id, 'system_id' => $os),
					'limit' => 6
			);
		}else {
			$this->paginate = array(
				'contain' => array(
					'Genre', 
					'System', 
					'Category'
				),
				'joins' =>array(
						array(
							'table' => 'games_genres',
							'alias' => 'GameGenre',
							'conditions' => 'GameGenre.game_id = Game.id'
						),
						array(
							'table' => 'genres',
							'alias' => 'Genre',
							'conditions' => 'GameGenre.genre_id = Genre.id'
						)
					),
					'conditions' => array('genre_id' => $id),
					'limit' => 6
			);
		}
		
		
		
		
		
		//pr( $this->paginate()); exit;
		$this->set('games', $this->paginate());
	}
	
	
	
	//view game by id
	public function view($id, $alias) {
	
		/* if($this->request->is('post'){
			$this->loadModel();
		} */
		
		$this->loadModel('Comment');
		$this->loadModel('Rate');
		
		//phan detect mobile
		$os = $this->getDevice();
		
		$this->Session->write('os', $os);
		$os = $this->Session->read('os');
		if ($os === ""){
			$os = $this->getDevice();
		}
		
		if($os == ''){
			$this->layout = 'detail';
		}
		
		if(!$id || !$this->Game->exists($id)){
			$this->Session->setFlash('Không có game này');
		}
		$game = $this->Game->find('first',
			array(
				'contain' => array('Genre', 'Category', 'Tag', 'System', 'Publisher', 'Image'),
				'conditions' =>array('Game.id' => $id)
			)
		);
		$comments = $this->Comment->find('all',
			array(
				'recursive' => 0,
				'conditions' => array('game_id' => $id),
				'order' => array('Comment.created' => 'DESC')
			)
		);
		$rate = $this->Rate->find('all', array('conditions' => array('game_id' => $id), 'recursive' => -1, 'fields' => array('SUM(Rate.point) as points')));
		$game_rate = $this->Rate->find('count',
			array(
				'conditions' => array('game_id' => $id
			)
		));
		
		$related_games = $this->Game->find('all',
			array(
				'contain' => array('Genre', 'Category', 'Tag', 'System', 'Publisher', 'Image'),
				'joins' =>array(
					array(
						'table' => 'games_genres',
						'alias' => 'GameGenre',
						'conditions' => 'GameGenre.game_id = Game.id'
					),
					array(
						'table' => 'genres',
						'alias' => 'Genre',
						'conditions' => 'GameGenre.genre_id = Genre.id'
					),
					array(
						'table' => 'games_categories',
						'alias' => 'GameCategory',
						'conditions' => 'GameCategory.game_id = Game.id'
					),
					array(
						'table' => 'categories',
						'alias' => 'Category',
						'conditions' => 'GameCategory.category_id = Category.id'
					)
				),
				'conditions' => array(
					'or' => array(
						'genre_id' => $game['Genre'][0]['id'],
					)
				),
				'limit' => 6,
				'order' => 'RAND()'
			)
		);
		$this->set(compact('game', 'comments', 'rate', 'related_games', 'game_rate'));
		$this->set('os', $os);
	}
	
	// search all game by tag
	public function get_game_by_tag($alias){
		$this->loadModel('Tag');
		if(!$alias){
			$this->Session->setFlash('Không có dữ liệu phù hợp');
		}else {
			$tag_games = $this->Tag->findByAlias($alias);
			$this->set(compact('tag_games'));
		}
	}
	
	//search
	public function search() {
		$notfound = false;
		if($this->request->is('post')){
			// pr($this->request->data);
			$system = $this->getDevice();
			$this->Session->write('os', $system);
			$os = $this->Session->read('os');
			
			if($os == '') {
				$keyword = $this->request->data['Game']['keyword'];
				$games = $this->Game->find('all',
					array(
						'contain' => array(
							'Genre', 
							'System', 
							'Category'
						),
						'order' => array('Game.created' => 'DESC'),
						'conditions' => array('Game.name like' => '%'.$keyword.'%')
					)
				);
			}else {
				$keyword = $this->request->data['Game']['keyword'];
				$games = $this->Game->find('all',
					array(
						'contain' => array(
							'Genre', 
							'System', 
							'Category'
						),
						'order' => array('Game.created' => 'DESC'),
						'joins' =>array(
							array(
								'table' => 'games_systems',
								'alias' => 'GameSystem',
								'conditions' => 'GameSystem.game_id = Game.id'
							),
							array(
								'table' => 'systems',
								'alias' => 'System',
								'conditions' => 'GameSystem.system_id = System.id'
							)
						),
						'conditions' => array('Game.name like' => '%'.$keyword.'%', 'system_id' => $os)
					)
				);
			}
			
			$this->set('os', $os);
			if(!empty($games)){
				$this->set(compact('games'));
				$notfound = true;
			}
			
		}
		$this->set(compact('keyword', 'notfound'));
	}
// check tag
	private function check_tag($tag_list = null) {
		$tags = explode(',', $tag_list);
		$this->loadModel('Tag');
		foreach($tags as $tag){
			$alias = $this->get_alias($tag);
			$tag_info = $this->Tag->findByAlias($alias);
			if(empty($tag_info)) {
				$data = array(
					'name' => ucwords(trim($tag)),
					'alias' => $alias
				);
				$this->Tag->create();
				$this->Tag->save($data);
				$save_info[] = $this->Tag->id;
			}else {
				$save_info[] = $tag_info['Tag']['id'];
			}
		}
		$this->request->data['Tag']['Tag'] = $save_info;
	}
	
	//Game system
	public function game_system($id, $alias) {
		$gamehot = $this->Game->find('all',
			array(
				'contain' => array(
					'System', 'Category', 'Genre'
				),
				'joins' =>array(
					array(
						'table' => 'games_systems',
						'alias' => 'GameSystem',
						'conditions' => 'GameSystem.game_id = Game.id'
					),
					array(
						'table' => 'systems',
						'alias' => 'System',
						'conditions' => 'GameSystem.system_id = System.id'
					)
				),
				'conditions' => array('system_id' => $id),
				'limit' => 6
			)
		);
		
		$gamenew = $this->Game->find('all',
			array(
				'contain' => array(
					'System', 'Category', 'Genre'
				),
				'joins' =>array(
					array(
						'table' => 'games_systems',
						'alias' => 'GameSystem',
						'conditions' => 'GameSystem.game_id = Game.id'
					),
					array(
						'table' => 'systems',
						'alias' => 'System',
						'conditions' => 'GameSystem.system_id = System.id'
					)
				),
				'conditions' => array('system_id' => $id),
				'limit' => 6,
				'order' => array('Game.id' => 'DESC')
			)
		);
		$this->set(compact('gamehot', 'gamenew'));
	}
	
	// game_download
	
	/* public function download($download=null){
		if($this->request->is('post')){
			$this->Game->id=$id;
			$user_id = $this->Auth->user();
			$this->loadModel('GamesSytem');
			$linkdown = $this->GamesSytem->find('first',array(
				 'conditions'=>array(
					//'Game.game_id'=>$id,
					'Game.download'=>$download
				 )
			 ));
			
			pr($linkdown);
			exit();
		}
	
	} */
}
